package com.gxa.saas.controller;

import com.gxa.saas.pojo.Client;
import com.gxa.saas.service.ClientService;
import com.gxa.saas.utils.JsonResult;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@ResponseBody
@RequestMapping("/client")
public class ClientController {
    @Autowired
    ClientService clientService;

    @ApiOperation("分页查询用户信息的方法")
    @RequestMapping(value = "/selectByPage", method = {RequestMethod.POST})
    public Map selectByPage(@RequestParam(value = "page") Integer page,
                            @RequestParam(value = "limit") Integer limit) {
        List<Client> clients = clientService.selectByPage(page, limit);
        List<Client> clients1 = clientService.selectAll();
        System.out.println(page);
        System.out.println(limit);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.set("totalCount",clients1.size());
        jsonResult.setData(clients);
        return jsonResult.getMap();
    }

    @ApiOperation("用手机号查询用户信息的方法")
    @RequestMapping(value = "/selectByPhone",method ={RequestMethod.POST})
    public Map selectByPhone(@RequestParam(value = "phone") String phone){
        Client client = clientService.selectByPhone(phone);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(client);
        return jsonResult.getMap();
    }

    @ApiOperation("导出用户信息的方法")
    @GetMapping(value = "/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<Client> clients = clientService.selectAll();
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("客户信息列表");
        String fileName = "客户信息列表.xls";
        // 将文件名中的中文部分被URL编码后的内容进行解析, 最终还是显示为中文状态
        fileName = URLEncoder.encode(fileName,"utf-8").replaceAll("\\+", "%20");
        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = { "编号","客户ID", "客户名称","客户类型","客户联系人","手机号","地址","创建人","负责人","创建时间"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把字段名添加到表头行上
            cell.setCellValue(text);
        }
        //准备将时间格式处理为标准日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        // 添加数据行:表头信息占用了第一行，所以要从第二行开始添加
        int rowNum = 1;
        for (Client item : clients) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(rowNum);
            dataRow.createCell(1).setCellValue(item.getCl_id());
            dataRow.createCell(2).setCellValue(item.getCl_name());
            dataRow.createCell(3).setCellValue(item.getCl_type());
            dataRow.createCell(4).setCellValue(item.getCl_contactperson());
            dataRow.createCell(5).setCellValue(item.getCl_phone());
            dataRow.createCell(6).setCellValue(item.getCl_address());
            dataRow.createCell(7).setCellValue(item.getCl_creatyperson());
            dataRow.createCell(8).setCellValue(item.getCl_leaderperson());
            dataRow.createCell(9).setCellValue(item.getCl_createtime());
            rowNum++;
        }
        //返回给前端下载
        //指定文档内容类型
        response.setContentType("application/octet-stream");
        //指定响应头
//        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
    @ApiOperation("添加用户信息的方法")
    @RequestMapping(value = "/insert",method ={RequestMethod.POST})
    public Map insert(Client client){
        Integer inert = clientService.inert(client);
//        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
//        Date date = new Date(System.currentTimeMillis());
//        System.out.println(formatter.format(date));
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("添加成功");
        jsonResult.setData(inert);
        return jsonResult.getMap();
    }
    @ApiOperation("修改用户信息的方法")
    @RequestMapping(value = "/update",method ={RequestMethod.POST})
    public Map update(Client client){
        clientService.update(client);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("修改成功");
        return jsonResult.getMap();
    }
    @ApiOperation("删除用户信息的方法")
    @RequestMapping(value = "/delete",method ={RequestMethod.POST})
    public Map delete(Integer id){
        clientService.delete(id);
        JsonResult jsonResult = new JsonResult();

        jsonResult.setCode("200");
        jsonResult.setMsg("删除成功");
        return jsonResult.getMap();
    }
    @ApiOperation("用多个字段查询用户信息的方法")
    @RequestMapping(value = "/selectByNameOrContactpersonOrCreatypersonOrLeaderperson",method ={RequestMethod.POST})
    public Map selectByNameOrContactpersonOrCreatypersonOrLeaderperson(@RequestParam(value = "name",required = false)String name,
                                                                       @RequestParam(value = "cl_phone",required = false)String cl_phone,
                                                                       @RequestParam(value = "from",required = false)String from,
                                                                       @RequestParam(value = "to",required = false)String to){

        Map map = new HashMap<>();
        map.put("name",name);
        map.put("cl_phone",cl_phone);
        map.put("from",from);
        map.put("to",to);
        List<Client> clients = clientService.selectByNameOrContactpersonOrCreatypersonOrLeaderperson(map);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.set("total",clients.size());
        jsonResult.setData(clients);
        return jsonResult.getMap();
    }
    @ApiOperation("上传图片的方法")
    @RequestMapping(value = "/upload",method ={RequestMethod.POST})
    public Map upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        System.out.println("originalFilename:" + originalFilename);
        // 从原始文件名中获取后缀,作为新添加的文件的文件名后缀(匹配)
        String subfix = originalFilename.substring(originalFilename.indexOf(".") + 1);
        System.out.println("subfix:" + subfix);
        //使用UUID作为文件名,保证服务器中存放的文件名唯一
        String targetFile = UUID.randomUUID().toString().replace("-", "") + "." + subfix;
        System.out.println("targetFile:" + targetFile);
        // 通过request获取当前程序的根路径"/"
        String path = request.getSession().getServletContext().getRealPath("/");
        // 通过绝对路径
        //String path =("E:");
        String fileName = path + "/upload/image/" + targetFile;
        System.out.println("fileName:" + fileName);
        // 构建文件对象
        File uploadFile = new File(fileName);
        //核心操作(含有异常操作, 利用异常设定状态码(和前端约定)
        // 此处应当和ExceptionController结合, 当try执行成功则设定状态码0
        // 出现异常则设定其他
        // 再将异常信息结合BusinessException抛出, 交给ExceptionController处 理
        try {
            multipartFile.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.set("pathFile",fileName);
        return jsonResult.getMap();
    }
    @ApiOperation("全部查询用户信息的方法")
    @RequestMapping(value = "/selectAll", method = {RequestMethod.POST})
    public Map selectAll() {
        List<Client> clients = clientService.selectAll();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(clients);
        return jsonResult.getMap();
    }
    @ApiOperation("上传excel的方法")
    @RequestMapping(value = "/uploadExecl",method ={RequestMethod.POST})
    public Map uploadExecl(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        System.out.println("originalFilename:" + originalFilename);
        // 从原始文件名中获取后缀,作为新添加的文件的文件名后缀(匹配)
        String subfix = originalFilename.substring(originalFilename.indexOf(".") + 1);
        System.out.println("subfix:" + subfix);
        //使用UUID作为文件名,保证服务器中存放的文件名唯一
        String targetFile = UUID.randomUUID().toString().replace("-", "") + "." + subfix;
        System.out.println("targetFile:" + targetFile);
        // 通过request获取当前程序的根路径"/"
        String path = request.getSession().getServletContext().getRealPath("/");
        // 通过绝对路径
        //String path =("E:");
        String fileName = path + "/upload/excel/" + targetFile;
        System.out.println("fileName:" + fileName);
        // 构建文件对象
        File uploadFile = new File(fileName);
        //核心操作(含有异常操作, 利用异常设定状态码(和前端约定)
        // 此处应当和ExceptionController结合, 当try执行成功则设定状态码0
        // 出现异常则设定其他
        // 再将异常信息结合BusinessException抛出, 交给ExceptionController处 理
        try {
            multipartFile.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.set("pathFile",fileName);
        jsonResult.setMsg("上传成功");
        return jsonResult.getMap();
    }
}
